Page({
    data: {
      isLogin: false,
      userInfo: null,
      errorMsg: '',
      loginCode: null // 存储登录code
    },
  
    onLoad() {
      // 检查本地存储中是否有token
      const token = wx.getStorageSync('token');
      const userInfo = wx.getStorageSync('userInfo');
      
      if (token && userInfo) {
        this.setData({
          isLogin: true,
          userInfo: userInfo
        });
      }
    },
  
    // 获取登录code
    getLoginCode() {
      const that = this;
      wx.login({
        success: (res) => {
          if (res.code) {
            that.setData({
              loginCode: res.code
            });
          } else {
            that.setData({
              errorMsg: '获取登录凭证失败：' + res.errMsg
            });
          }
        },
        fail: (err) => {
          that.setData({
            errorMsg: '登录失败：' + err.errMsg
          });
        }
      });
    },
  
    // 获取用户信息
    onGetUserInfo(e) {
      const that = this;
      const userInfo = e.detail.userInfo;
      const code = this.data.loginCode;
      
      if (!userInfo) {
        that.setData({
          errorMsg: '获取用户信息失败：用户拒绝了授权'
        });
        return;
      }
      
      if (!code) {
        that.setData({
          errorMsg: '请先点击登录按钮获取登录凭证'
        });
        return;
      }
      
      // 发送登录请求到后端
      wx.request({
        url: 'http://192.168.0.100:33888/auth/login', // 替换为你的后端地址
        method: 'POST',
        data: {
          code: code,
          userInfo: userInfo
        },
        success: (res) => {
          if (res.statusCode === 200 && res.data.code === 200) {
            // 登录成功
            const token = res.data.token;
            const userInfo = res.data.userInfo;
            
            // 存储token和用户信息
            wx.setStorageSync('token', token);
            wx.setStorageSync('userInfo', userInfo);
            
            // 更新全局数据
            getApp().globalData.token = token;
            getApp().globalData.userInfo = userInfo;
            
            // 更新页面状态
            that.setData({
              isLogin: true,
              userInfo: userInfo,
              errorMsg: ''
            });
          } else {
            that.setData({
              errorMsg: '登录失败：' + (res.data.msg || '服务器错误')
            });
          }
        },
        fail: (err) => {
          that.setData({
            errorMsg: '请求失败：' + err.errMsg
          });
        }
      });
    },
  
    // 退出登录
    logout() {
      // 清除本地存储
      wx.removeStorageSync('token');
      wx.removeStorageSync('userInfo');
      
      // 清除全局数据
      getApp().globalData.token = null;
      getApp().globalData.userInfo = null;
      
      // 更新页面状态
      this.setData({
        isLogin: false,
        userInfo: null
      });
      
      // 重新获取登录code
      this.getLoginCode();
    }
  });